#include"myshell.h"
#include<iostream>
char* gargv[ARGS]={0};
int gargc=0;
char pwd[1028];//全局变量空间，保存shell进程的工作路径
int lastcode = 0;
void Debug()
{
    printf("error\n");
}
static std::string GetUserName()
{
    const char *home = getenv("HOME");
    return (home == nullptr) ? "None" : home;
}
static std::string GetHostName()
{
    const char * hostname = getenv("HOSTNAME");
    return (hostname == nullptr)?"None":hostname;
}
static std::string GetPwd()
{
    // const char * pwd = getenv("PWD");
    // return (pwd == nullptr)?"None":pwd;
    char temp[1024];
    getcwd(temp,sizeof(temp));
    //顺便更新一下shell自己的环境变量
    snprintf(pwd,sizeof(pwd),"PWD=%s",temp);
    putenv(pwd);

    //只显示当前工作路径
    std::string pwd_lable = temp;
    const std::string pathsep = "/";
    auto pos =pwd_lable.rfind(pathsep);
    if(pos==std::string::npos)
    {
        return "None";
    }
    pwd_lable = pwd_lable.substr(pos+pathsep.size());
    return pwd_lable.empty() ? "/": pwd_lable;
}
static std::string GetHomePath()
{
    const char* home=getenv("HOME");
    return (home==nullptr)?"/":home;
}
//1.输出提示符
 void  PrintCommandPrompt()
 {
    std::string username = GetUserName();
    std::string hostname = GetHostName();
    std::string pwd = GetPwd();
    printf("[%s@%s %s]#",username.c_str(),hostname.c_str(),pwd.c_str());
 }

 //2.获取用户的键盘输入
bool GetCommandString(char cmd_str_buff[],int len)
{
    if(cmd_str_buff==nullptr || len<=0)
    return false;

    //一定有数据,回车/空格也是数据
    char* ret = fgets(cmd_str_buff,len,stdin);
    //防止空格
    if(ret==nullptr)
        return false;
    cmd_str_buff[strlen(cmd_str_buff)-1]=0;
    //防止回车
    return strlen(cmd_str_buff)==0?false:true;

}
//3.解析命令，形成命令行参数表
bool ParseCommandString(char cmd[])
{
    if(cmd==nullptr)
        return false;
    //解析后的字符串变成一个个命令行参数
    //所以要拿个东西来存它
#define SEP " "
    gargv[gargc++]=strtok(cmd,SEP);
    while((bool)(gargv[gargc++]=strtok(NULL,SEP)));
    //减去\n的次数
    gargc--;
    return true;
}
//4.初始化命令行参数表
void InitGlobal()
{
    gargc=0;
    memset(gargv,0,sizeof(gargv));
}
 //5.执行命令
 void ForkAndExec()
 {
    pid_t id = fork();
    if(id<0)
    {
        perror("fork");
        return;
    }
    else if(id==0)
    {
        //子进程
        execvp(gargv[0],gargv);
        exit(0);
    }
    else{
        //父进程
        int status=0;
        pid_t rid =waitpid(id,&status,0);
        if(rid>0)
        {

        }

    }
 }
 //6.内建命令判断
bool BuiltInCommandExec()
{
    //内建命令：shell自己执行的命令，如同shell执行一个自己的函数
    std::string cmd=gargv[0];
    bool ret=true;
    if(cmd=="cd")
    {
        if(gargc==2)
        {
            std::string target = gargv[1];
            if(target=="~")
            {
                ret=true;
                chdir(GetHomePath().c_str());
            }
            else{
                //Bug
            }
        }
        else if(gargc==1)
        {
            ret=true;
            chdir(GetHomePath().c_str());
        }
        else{
            //Bug
        }
    }
    else if(cmd=="echo")
    {
        if(gargc==2)
        {
            std::string args=gargv[1];
            if(args[0]=='$')
            {
                if(args[1]=='?')
                {
                    printf("lastcode:%d\n",lastcode);
                    lastcode=0;
                    ret=true;
                }
                else{
                    const char* name=&args[1];
                    printf("%s\n",getenv(name));
                    lastcode = 0;
                    ret = true;
                }
            }
            else{
                printf("%s\n",args.c_str());
                ret = true;
            }
        }
  
    }
    return ret;
}